﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CI.Models;
using CI.Models.Data;
using CI.Models.Production;
using CI.Models.Production.Interfaces;
using log4net;
using XmlModelPackager;

namespace PICLI
{
    public class PIGenerator: XmlGeneratorBase, IXmlGenerator
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(PIGenerator));
        public PIGenerator() : base(new FileInfo("PI.xml"), "PI")
        {
        }

        public IJobModelManager Manager { get; set; }

        public void GenerateXml()
        {
            foreach(var job in Manager.ManagedChains)
                WriteJob(job as IIndustryJob);
        }

        public void WriteJob(IIndustryJob job)
        {
            BeginElement("Job");

            WriteAttribute(job.Runs, "Runs");
            WriteAttribute(job.SetupCost, "SetupCost");

            WriteQuantityCalculator(job.Cost, "Cost");
            WriteQuantityCalculator(job.Time, "Time");
            WriteIndustryProduct(job.Output, "Output");

            foreach (var childJob in job.GetChildJobs<IIndustryJob>())
                WriteJob(childJob);

            EndElement();
        }

        public void WriteIndustryProduct(IIndustryProduct product, string elementName)
        {
            BeginElement(elementName);

            WriteAttribute(product.Item.TypeName, "ItemName");
            WriteQuantityCalculator(product.Quantity, "Quantity");

            EndElement();
        }

        public void WriteQuantityCalculator<T>(IQuantityCalculator<T> quantity, string elementName)
        {
            BeginElement(elementName);

            WriteAttribute(quantity.PerRun, "PerRun");
            WriteAttribute(quantity.Runs, "Runs");
            WriteAttribute(quantity.Total, "Total");

            EndElement();
        }
    }
}
